package com.lnhuachuan.iotmodbusrtu;


import com.lnhuachuan.iotmodbusrtu.config.ModbusConfig;
import com.lnhuachuan.iotmodbusrtu.config.ModbusMasterConfig;
import com.lnhuachuan.iotmodbusrtu.entity.exception.ConnectionException;
import com.lnhuachuan.iotmodbusrtu.handler.exmple.ModbusRequestHandlerExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author heyayun
 * @description TODO
 * @date 2021/3/23 14:40
 */
@Slf4j
@Component
public class ModbusMasterServer {

    @Autowired
    private ModbusRequestHandlerExample modbusRequestHandlerExample;

    @Bean
    public ModbusServer start() {
        ModbusMasterConfig config = ModbusMasterConfig
                .builder("0.0.0.0")
                .setPort(9905)
                .build();
        ModbusServer modbusServer = new ModbusServer(config);
        try {
            modbusServer.setup(modbusRequestHandlerExample);
            System.out.println("ModbusServer started ==========================================");
            log.info("Modbus started on port(s): {}", 9905);
            log.info("Modbus Server Start !!!!!!");
            return modbusServer;
        } catch (ConnectionException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
}
